package com.sprinboot_vue.blog_springboot.controller;

import com.sprinboot_vue.blog_springboot.entity.Tag;
import com.sprinboot_vue.blog_springboot.repository.TagRepository;
import com.sprinboot_vue.blog_springboot.result.Result;
import com.sprinboot_vue.blog_springboot.result.ResultInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * @author Thomas
 * @version 1.0
 * @date 2021/11/22 12:50
 */
@RestController
@RequestMapping("/tag")
@Api(tags = "标签名管理")
public class TagHandler {
    @Autowired
    private TagRepository tagRepository;

    @PostMapping("/addTag/{tag}")
    @ApiOperation("添加标签名")
    public Result addTag(@PathVariable("tag") String tag){
        long id = tag.hashCode();
        Tag tag1=new Tag();
        tag1.setTag(tag);
        tag1.setId(id);
        tag1.setTag_number(0);
        Optional<Tag> byId = tagRepository.findById(id);
        if(!byId.isPresent()){//如果查询为空则可以添加
            try{
                tagRepository.save(tag1);
                return Result.success().codeAndmessage("200","添加成功!");
            }catch (Exception e){
                return Result.error().codeAndmessage("404","出现未知错误!");
            }
        }else{
            return Result.error().codeAndmessage("404","已经存在此标签名!");
        }
    }

    @GetMapping("/fondTag/{page}/{pageSize}")
    @ApiOperation("分页查询标签名")
    public Result findTag(@PathVariable("page") int page,@PathVariable("pageSize") int pageSize){
        Pageable pageable= PageRequest.of(page-1,pageSize);
        return 	Result.success().codeAndmessage(ResultInfo.SUCCESS).date("data",tagRepository.findAll(pageable));
    }

    @DeleteMapping("/deleteTagById/{tag}")
    @ApiOperation("删除标签名")
    public Result deleteTagById(@PathVariable("tag") String tag_str){
        long id=(long)tag_str.hashCode();
        try{
            tagRepository.deleteById(id);
            return Result.success().codeAndmessage(ResultInfo.DELETE);
        }catch (Exception e){
            return Result.error().codeAndmessage(ResultInfo.ERROR);
        }
    }

    @GetMapping("/findAllTag")
    @ApiOperation("返回所有的标签")
    public Result findAllTag(){
        List<Tag> all = tagRepository.findAll();
        return Result.success().codeAndmessage(ResultInfo.SUCCESS).date("data",all);
    }
}
